package com.nineclock.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nineclock.common.constant.NcConstant;
import com.nineclock.common.constant.SysCompanyContactConfigConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.common.utils.CurrentUserHolder;
import com.nineclock.system.dto.SysCompanyContactConfigDTO;
import com.nineclock.system.mapper.SysCompanyContactConfigMapper;
import com.nineclock.system.pojo.SysCompanyContactConfig;
import com.nineclock.system.service.SysCompanyContactConfigService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Transactional
@Service
public class SysCompanyContactConfigServiceImpl extends ServiceImpl<SysCompanyContactConfigMapper, SysCompanyContactConfig> implements SysCompanyContactConfigService {

    @Override
    public void add(SysCompanyContactConfigDTO dto) {

        //判断参数是否为有效参数
        if(dto == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //判断用户是否登录
        Long userId = CurrentUserHolder.get().getId();
        if(userId == null){
            throw new NcException(ResponseEnum.UNAUTHORIZED);
        }

        //判断是否有重复的字段，防止重复添加
        int size = this.list().stream().filter(p -> p.getName().equals(dto.getName())).collect(Collectors.toList()).size();
        if(size != 0){
            throw new NcException(ResponseEnum.INSERT_OPERATION_FAIL,dto.getName() + "已经存在，无法重复添加");
        }

        //增加字段
        SysCompanyContactConfig sccc = BeanHelper.copyProperties(dto, SysCompanyContactConfig.class);
        sccc.setCompanyId(CurrentUserHolder.get().getCompanyId());
        sccc.setFieldType("string");
        sccc.setStatus((short)1);
        this.save(sccc);

    }

    /**
     * 思路：
     * 1.查询公司ID下的所有通讯录配置
     * 2.如果查询为NULL，则初始化默认的通讯录配置关联到改公司下存入表中
     * 3.如果查询不为NULL，则直接返回
     * @return
     */
    @Override
    public List<SysCompanyContactConfig> findList() {

        List<SysCompanyContactConfig> dtoList = new ArrayList<>();

        long companyId = 1L; //默认用户ID
        LambdaQueryWrapper<SysCompanyContactConfig> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysCompanyContactConfig::getCompanyId,companyId);

        List<SysCompanyContactConfig> scccList = this.list(lambdaQueryWrapper);

        //如果企业没有设置通讯录字段, 需要初始化默认值
        if(CollectionUtil.isEmpty(scccList)){
            scccList = new ArrayList<>();
            for (String name : NcConstant.COMPANY_CONFIG_CONTACT_LIST) {
                SysCompanyContactConfig config = new SysCompanyContactConfig();
                config.setCompanyId(companyId);
                config.setName(name);
                config.setType("fixed");
                config.setStatus((short)1);
                config.setFieldType("string");

                this.save(config);

                scccList.add(config);
            }
        }

        return scccList;
    }

    @Override
    public void update(Long id, Short status) {

        //判断参数是否为有效参数
        if(id == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //判断用户是否登录
        Long userId = CurrentUserHolder.get().getId();
        if(userId == null){
            throw new NcException(ResponseEnum.UNAUTHORIZED);
        }

        SysCompanyContactConfig sysCompanyContactConfig = new SysCompanyContactConfig();
        sysCompanyContactConfig.setStatus(status);
        sysCompanyContactConfig.setId(id);
        boolean result = this.updateById(sysCompanyContactConfig);
        if(!result){
            throw new RuntimeException("更新失败");
        }
    }

    @Override
    public void delete(Long id) {

        //判断参数是否为有效参数
        if(id == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //判断用户是否登录
        Long userId = CurrentUserHolder.get().getId();
        if(userId == null){
            throw new NcException(ResponseEnum.UNAUTHORIZED);
        }

        //查询目标记录
        SysCompanyContactConfig sysCompanyContactConfig = this.getById(id);

        //如果没有查询到该记录
        if(sysCompanyContactConfig == null){
            throw new NcException(ResponseEnum.DELETE_OPERATION_FAIL,"企业通讯录-删除失败-没有该字段");
        }

        //如果该记录正在被固定，则无法删除该记录
        if(SysCompanyContactConfigConstant.TYPE_FIXED.equals(sysCompanyContactConfig.getType())){
            throw new NcException(ResponseEnum.DELETE_OPERATION_FAIL,"企业通讯录-删除失败-该字段正在被固定");
        }

        //如果该记录正在被使用，则无法删除该记录
        if(SysCompanyContactConfigConstant.STATUS_YES.equals(sysCompanyContactConfig.getStatus())){
            throw new NcException(ResponseEnum.DELETE_OPERATION_FAIL,"企业通讯录-删除失败-该字段正在被使用");
        }

        //删除该记录
        this.removeById(id);

    }

}
